﻿namespace WinServiceManagerTool
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Forms;

    internal static class Program
    {
        private const int GWL_EXSTYLE = -20;
        private const int SW_HIDE = 0;
        private const int SW_RESTORE = 9;
        private const int SW_SHOWNA = 8;
        private const int WS_EX_APPWINDOW = 0x40000;

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindowA(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        private static extern bool GetClassNameA(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
        [DllImport("user32.dll")]
        private static extern int GetWindowLongA(IntPtr hwnd, int nIndex);
        [STAThread]
        private static void Main()
        {
            IntPtr hwnd = FindWindowA(null, "华伟服务监控");
            if (hwnd == IntPtr.Zero)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
    
                Application.Run(new Form1());
            }
            else
            {
                int windowLongA = GetWindowLongA(hwnd, -20);
                if ((windowLongA & 0x40000) == 0)
                {
                    ShowWindowAsync(hwnd, 0);
                    windowLongA |= 0x40000;
                    SetWindowLongA(hwnd, -20, windowLongA);
                }
                ShowWindowAsync(hwnd, 9);
                SetForegroundWindow(hwnd);
            }
        }

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern int SetWindowLongA(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    }
}

